<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #box {
            margin: 100px auto 0;
            width: 200px;
            height: 200px;
            border: 2px solid dodgerblue;
            position: relative;
        }


        #box.active {
            border: 2px dashed skyblue;
        }

        #box.active::before {
            content: '拖入上传';
            position: absolute;
            width: 100%;
            height: 100%;
            font: 400 25px/200px '宋体';
            color: #ddd;
            background: rgba(55, 55, 55, .4);
            text-align: center;
        }

        #img {
            width: 100%;
            height: 100%;
        }


        #file {
            top: 0;
            position: absolute;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }

        #fileName {
            position: absolute;
            bottom: - 30px;
            width: 100%;
            height: 30px;
            font: 400 20px/30px '宋体';
            text-align:center;
        }
    </style>
</head>

<body>
    <div id="box">
        <img src="" alt="" id="img">
        <input type="file" id="file">
        <span id="fileName">文件名</span>
    </div>

    <script>
        //阻止拖拽区的默认事件
        file.ondragover = function (e) {
            e.preventDefault();
            box.classList.add('active');
        };
        file.ondragleave = function (e) {
            box.classList.remove('active');
        };
        //阻止释放的默认事件
        file.ondrop = function (e) {
            e.preventDefault();
            //获取传来的图片
            var fileObj = e.dataTransfer.files[0];
            //文件过滤
            if (fileObj.type.indexOf('image') < 0) {
                console.log('不是图片文件');
                box.classList.remove('active');
                return;
            }
            if (Math.floor(fileObj.size / 1024) > 2000) {
                console.log('文件大于2M');
                box.classList.remove('active');
                return;
            }
            //文件读取
            var reader = new FileReader;
            reader.readAsDataURL(fileObj);
            reader.onload = function () {
                img.src = this.result;
                fileName.innerHTML = fileObj.name;
                file.files[0] = fileObj;
                box.classList.remove('active');
            };
        };
    </script>






</body>

</html>